//
//  LKSportTrack.m
//  SportDemo
//
//  Created by Lukj on 2017/4/22.
//  Copyright © 2017年 lukj. All rights reserved.
//

#import "LKSportTrack.h"
#import "LKSportSpeaker.h"
@implementation LKSportTrack {
    //  记录每一段折线的起点
    CLLocation *_source;
    //  折线的集合
    NSMutableArray<LKSportPolyline *> *_polylines;
    //  记录每一段折线的时间
    CLLocation *_preGPSLocation;
    LKSportSpeaker *_speaker;
}

@synthesize totalTime = _totalTime;
@synthesize totalDistace = _totalDistace;
@synthesize maxSpeed = _maxSpeed;
@synthesize avgSpeed = _avgSpeed;
//  初始化方法
- (instancetype)initWithSportTrackType:(SportTrackType)sportTrackType andSportState:(SportState)sportState
{
    self = [super init];
    if (self) {
        //  记录运动的类型
        _sportTrackType = sportTrackType;
        
        switch (sportTrackType) {
            case SportTrackTypeRuning:
                _pointAnnotationImageName = @"map_annotation_run";
                break;
            case SportTrackTypebicycling:
                _pointAnnotationImageName = @"map_annotation_bike";
                break;
            case SportTrackTypewalking:
                _pointAnnotationImageName = @"map_annotation_walk";
                break;
            default:
                break;
        }
        
        //  记录运动的状态
        _sportState = sportState;
        _polylines = [NSMutableArray array];
        //  创建播报器
        _speaker = [[LKSportSpeaker alloc] init];
        //  播报运动的类型
        [_speaker startSportWithSportType:_sportTrackType];
    }
    return self;
}

//  添加折线
- (LKSportPolyline *)appendPolylineDest:(CLLocation *)dest{
    
    //  整距离播报
    [_speaker speakerSportWithDistance:_totalDistace andTime:_totalTime andAvgSpeed:_avgSpeed];
    
    
    //  计算GPS强度, 如果GPS差/断开, 则不生成折线
    if ([self calculateGPSWithLocation:dest] < SportMapGPSStateNormal) {
        
        return nil;
    }
    
    
    //判断运动状态
    if (self.sportState != SportStateContinue) {
        //暂停/结束运动时,停止生成折线
        //清空记录的折线起点
        _source = nil;
        return nil;
    }
    
//    //  判断是否移动 速度 = 0表示没有在移动, 速度为负值, 表示在室内, GPS受干扰, 速度无效
//    if (dest.speed == 0) {
//        return nil;
//    }

//    //排除已经"过期"的定位数据  计算当前时间和定位时间戳的差值  2秒以内的数据可用
//    if ([[NSDate date] timeIntervalSinceDate:dest.timestamp] >= 2) {
//        
//        return nil;
//    }
    
    //  判断首次调用
    if (_source == nil) {
        //  记录起点
        _source = dest;
        
        //  创建起点大头针模型
        _pointAnnotation = [[MAPointAnnotation alloc] init];
        //  设置大头针起点位置
        _pointAnnotation.coordinate = dest.coordinate;
        
        return nil;
    }
    
    LKSportPolyline *polyline = [LKSportPolyline polylineWithSourceLocation:_source andWithDestLocation:dest];
    
    //  将折线模型进行记录
    [_polylines addObject:polyline];
    
    //  记录下一段起点
    _source = dest;
    
    return polyline;

}

//  计算GPS状态
- (SportMapGPSState)calculateGPSWithLocation:(CLLocation *)location {
    
    SportMapGPSState state = SportMapGPSStateBad;
    
    if (location.speed < 0) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LKSprotGPSStateChangeNote" object:nil userInfo:@{@"LKSprotGPSStateChangeNoteGPSStateKey": @(state)}];
        
        return state;
    }
    
    if (_preGPSLocation == nil) {
        
        _preGPSLocation = location;
        return state;
    }
    
    //  GPS时间差
    double deltatime = ABS([location.timestamp timeIntervalSinceDate:_preGPSLocation.timestamp] - 1);
    
    if (deltatime > 1) { // GPS差
        
    }else if (deltatime <= 1 && deltatime >= 0.01) { // GPS正常
        state = SportMapGPSStateNormal;
    }else { //  GPS好
        state = SportMapGPSStateGood;
    }
    
    _preGPSLocation = location;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LKSprotGPSStateChangeNote" object:nil userInfo:@{@"LKSprotGPSStateChangeNoteGPSStateKey": @(state)}];
    return state;
    
}


#pragma mark - get & set

- (void)setSportState:(SportState)sportState {
    
    _sportState = sportState;
    //  播报运动的状态
    [_speaker speakerSportState:sportState];
    
}
- (CGFloat)totalTime {
    //  求集合中元素的某个属性的和, 可以使用kvc来进行计算
    _totalTime = [[_polylines valueForKeyPath:@"@sum.time"] floatValue];
    return _totalTime;
    
}

- (CGFloat)totalDistace {
    //  求集合中元素的某个属性的和, 可以使用kvc来进行计算
    _totalDistace = [[_polylines valueForKeyPath:@"@sum.distance"] floatValue];
    return _totalDistace;
}

- (CGFloat)maxSpeed {
    //  求集合中元素的某个属性的和, 可以使用kvc来进行计算
    _maxSpeed = [[_polylines valueForKeyPath:@"@max.speed"] floatValue];
    return _maxSpeed;
}

- (CGFloat)avgSpeed {
    //  求集合中元素的某个属性的和, 可以使用kvc来进行计算
    _avgSpeed = [[_polylines valueForKeyPath:@"@avg.speed"] floatValue];
    return _avgSpeed;
}

- (NSString *)totalTimeStr {
    
    int time = (int)_totalTime;
    return [NSString stringWithFormat:@"%02d:%02d:%02d", time / 3600, (time % 3600) / 60, time % 60];
}


@end
